package com.hiultra.archive.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hiultra.archive.domain.*;
import com.hiultra.archive.domain.vo.ArchiveBoxinnerMoveTaskIssuedVo;
import com.hiultra.archive.domain.vo.ArchiveBoxinnerMoveTaskReportVo;
import com.hiultra.archive.domain.vo.ArchiveDesTaskIssuedVo;
import com.hiultra.archive.domain.vo.ResultEntity;
import com.hiultra.archive.mapper.*;
import com.hiultra.archive.service.IArchiveBoxinnerMoveService;
import com.hiultra.archive.service.IArchiveBoxinnerMoveTaskService;
import com.hiultra.archive.utils.sgsm.SM2Util;
import com.hiultra.archive.utils.tool.ToolUtils;
import com.hiultra.common.constant.BusinessConstants;
import com.hiultra.common.exception.ServiceException;
import com.hiultra.common.utils.DateUtils;
import com.hiultra.common.utils.uuid.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;

/**
 * 盒间移位任务Service业务层处理
 *
 * @author 派大星
 * @date 2024-07-23
 */
@Service
public class ArchiveBoxinnerMoveTaskServiceImpl implements IArchiveBoxinnerMoveTaskService {
    private static final Logger log = LoggerFactory.getLogger(ArchiveDesTaskServiceImpl.class);
    @Autowired
    private ArchiveBoxinnerMoveTaskMapper archiveBoxinnerMoveTaskMapper;
    @Autowired
    private ArchiveBoxinnerMoveMapper archiveBoxinnerMoveMapper;
    @Value("${priKey}")
    private String priKey;
    @Value("${pubKey}")
    private String pubKey;
    @Value("${urlIp}")
    private String urlIp;
    @Autowired
    private IArchiveBoxinnerMoveService archiveBoxinnerMoveService;
    @Autowired
    private RoomArchiveMapper roomArchiveMapper;
    @Autowired
    private ArcBoxMapper arcBoxMapper;
    @Autowired
    private ArchiveBagMapper archiveBagMapper;
    @Autowired
    private ArchiveBoxStatusMapper archiveBoxStatusMapper;

    /**
     * 查询盒间移位任务
     *
     * @param taskId 盒间移位任务主键
     * @return 盒间移位任务
     */
    @Override
    public ArchiveBoxinnerMoveTask selectArchiveBoxinnerMoveTaskByTaskId(String taskId) {
        return archiveBoxinnerMoveTaskMapper.selectArchiveBoxinnerMoveTaskByTaskId(taskId);
    }

    /**
     * 根据移位单号查询盒间移位任务
     *
     * @param archMoveNo 盒间移位任务单号
     * @return 盒间移位任务
     */
    @Override
    public ArchiveBoxinnerMoveTask selectArchiveBoxinnerMoveTaskByTaskNo(String archMoveNo) {
        return archiveBoxinnerMoveTaskMapper.selectArchiveBoxinnerMoveTaskByArchMoveNo(archMoveNo);
    }

    /**
     * 查询盒间移位任务列表
     *
     * @param archiveBoxinnerMoveTask 盒间移位任务
     * @return 盒间移位任务
     */
    @Override
    public List<ArchiveBoxinnerMoveTask> selectArchiveBoxinnerMoveTaskList(ArchiveBoxinnerMoveTask archiveBoxinnerMoveTask) {
        return archiveBoxinnerMoveTaskMapper.selectArchiveBoxinnerMoveTaskList(archiveBoxinnerMoveTask);
    }

    /**
     * 新增盒间移位任务
     *
     * @param archiveBoxinnerMoveTask 盒间移位任务
     * @return 结果
     */
    @Override
    public int insertArchiveBoxinnerMoveTask(ArchiveBoxinnerMoveTask archiveBoxinnerMoveTask) {
        return archiveBoxinnerMoveTaskMapper.insertArchiveBoxinnerMoveTask(archiveBoxinnerMoveTask);
    }

    /**
     * 修改盒间移位任务
     *
     * @param archiveBoxinnerMoveTask 盒间移位任务
     * @return 结果
     */
    @Override
    public int updateArchiveBoxinnerMoveTask(ArchiveBoxinnerMoveTask archiveBoxinnerMoveTask) {
        return archiveBoxinnerMoveTaskMapper.updateArchiveBoxinnerMoveTask(archiveBoxinnerMoveTask);
    }

    /**
     * 批量删除盒间移位任务
     *
     * @param taskIds 需要删除的盒间移位任务主键
     * @return 结果
     */
    @Override
    public int deleteArchiveBoxinnerMoveTaskByTaskIds(String[] taskIds) {
        return archiveBoxinnerMoveTaskMapper.deleteArchiveBoxinnerMoveTaskByTaskIds(taskIds);
    }

    /**
     * 删除盒间移位任务信息
     *
     * @param taskId 盒间移位任务主键
     * @return 结果
     */
    @Override
    public int deleteArchiveBoxinnerMoveTaskByTaskId(String taskId) {
        return archiveBoxinnerMoveTaskMapper.deleteArchiveBoxinnerMoveTaskByTaskId(taskId);
    }

    /**
     * 盒间移位任务下发接口
     *
     * @param data
     * @return 结果
     */
    @Override
    public ResultEntity insertIssuedArchiveBoxinnerMoveTask(String data) throws ParseException {
        //解密
        System.out.println("盒间移位任务数据：" + data);
        String decryptedResult = new SM2Util().decryptBySM2(data, priKey);
        System.out.println("盒间移位任务解密结果：" + decryptedResult);
        ArchiveBoxinnerMoveTaskIssuedVo archiveBoxinnerMoveTaskIssuedVo = JSON.parseObject(decryptedResult.trim(), ArchiveBoxinnerMoveTaskIssuedVo.class);
        System.out.println("盒间档案移位查询成功");
        if (ObjectUtil.isNull(archiveBoxinnerMoveTaskIssuedVo)) {
            // 返回错误信息或抛出异常
            log.info("入参解析出错，请检查重试");
            return ResultEntity.error("入参解析出错，请检查重试");
        }
        try {
            processArchiveBoxinnerMoveTask(archiveBoxinnerMoveTaskIssuedVo);
        } catch (ServiceException e) {
            e.printStackTrace();
            return ResultEntity.error(e.getMessage());
        }

        return ResultEntity.success();
    }


    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void processArchiveBoxinnerMoveTask(ArchiveBoxinnerMoveTaskIssuedVo archiveBoxinnerMoveTaskIssuedVo) throws ServiceException {
        try {
            ArchiveBoxinnerMoveTask archiveBoxinnerMoveTask = ToolUtils.convertEntity(archiveBoxinnerMoveTaskIssuedVo, ArchiveBoxinnerMoveTask::new);

            ArchiveBoxinnerMoveTask archiveBoxinnerMoveTask1 = selectArchiveBoxinnerMoveTaskByTaskNo(archiveBoxinnerMoveTask.getArchMoveNo());

            archiveBoxinnerMoveTask.setMoveStatus(BusinessConstants.BOX_MOVE_STATUS);
            if (null == archiveBoxinnerMoveTask1) {
                //taskId唯一主键
                archiveBoxinnerMoveTask.setTaskId(UUID.randomUUID().toString().replace("-", ""));
                insertArchiveBoxinnerMoveTask(archiveBoxinnerMoveTask);
                List<ArchiveBoxinnerMoveTaskIssuedVo.ArchMoveInfo> archiveBoxinnerMoveList = archiveBoxinnerMoveTaskIssuedVo.getArchMoveList();

                if (archiveBoxinnerMoveList.size() > 0) {
                    for (ArchiveBoxinnerMoveTaskIssuedVo.ArchMoveInfo archiveBoxinnerMove : archiveBoxinnerMoveList) {
                        //根据下发的档案处理数据
                        ArchiveBoxinnerMove archiveBoxinnerMove1 = ToolUtils.convertEntity(archiveBoxinnerMove, ArchiveBoxinnerMove::new);
                        //查询档案信息
                        RoomArchive roomArchive = roomArchiveMapper.selectRoomArchiveById(archiveBoxinnerMove.getArchiveId());

                        if (ObjectUtil.isNull(roomArchive)) {
                            log.info("档案标识" + archiveBoxinnerMove.getArchiveId() + "不存在");
                            throw new ServiceException("档案标识" + archiveBoxinnerMove.getArchiveId() + "不存在，请检查后重试！");
                        }
                        archiveBoxinnerMove1.setArchName(roomArchive.getArchiveName());
                        //根据盒id查询盒号
                        ArcBox arcBox = arcBoxMapper.selectArcBoxByBoxId(archiveBoxinnerMove.getNewBoxId());
                        if (ObjectUtil.isNull(arcBox)) {
                            log.info("档案盒标识" + archiveBoxinnerMove.getNewBoxId() + "不存在");
                            throw new ServiceException("档案盒标识" + archiveBoxinnerMove.getNewBoxId() + "不存在，请检查后重试！");
                        }
                        //根据袋id查询袋号
                        //判断是否为空
                        if (ObjectUtil.isNotNull(archiveBoxinnerMove.getNewBagId())) {
                            ArchiveBag arcBag = archiveBagMapper.selectArchiveBagByBagId(archiveBoxinnerMove.getNewBagId());
                            if (ObjectUtil.isNull(arcBag)) {
                                log.info("档案袋标识" + archiveBoxinnerMove.getNewBagId() + "不存在");
                                throw new ServiceException("档案袋标识" + archiveBoxinnerMove.getNewBagId() + "不存在，请检查后重试！");
                            }
                        }

                        archiveBoxinnerMove1.setMoveStatus(BusinessConstants.BOX_MOVE_STATUS);
                        archiveBoxinnerMove1.setId(UUID.randomUUID().toString().replace("-", ""));
                        archiveBoxinnerMove1.setTaskId(archiveBoxinnerMoveTask.getTaskId());
                        archiveBoxinnerMoveService.insertArchiveBoxinnerMove(archiveBoxinnerMove1);
                    }
                }
            } else {
                updateArchiveBoxinnerMoveTask(archiveBoxinnerMoveTask);
                List<ArchiveBoxinnerMoveTaskIssuedVo.ArchMoveInfo> archiveBoxinnerMoveList = archiveBoxinnerMoveTaskIssuedVo.getArchMoveList();
                if (archiveBoxinnerMoveList.size() > 0) {
                    for (ArchiveBoxinnerMoveTaskIssuedVo.ArchMoveInfo archiveBoxinnerMove : archiveBoxinnerMoveList) {
                        //根据下发的档案处理数据
                        ArchiveBoxinnerMove archiveBoxinnerMove1 = ToolUtils.convertEntity(archiveBoxinnerMove, ArchiveBoxinnerMove::new);
                        //查询档案信息
                        RoomArchive roomArchive = roomArchiveMapper.selectRoomArchiveById(archiveBoxinnerMove.getArchiveId());

                        if (ObjectUtil.isNull(roomArchive)) {
                            log.info("档案标识" + archiveBoxinnerMove.getArchiveId() + "不存在");
                            throw new ServiceException("档案标识" + archiveBoxinnerMove.getArchiveId() + "不存在，请检查后重试！");
                        }
                        archiveBoxinnerMove1.setArchName(roomArchive.getArchiveName());
                        //根据盒id查询盒号
                        ArcBox arcBox = arcBoxMapper.selectArcBoxByBoxId(archiveBoxinnerMove.getNewBoxId());
                        if (ObjectUtil.isNull(arcBox)) {
                            log.info("档案盒标识" + archiveBoxinnerMove.getNewBoxId() + "不存在");
                            throw new ServiceException("档案盒标识" + archiveBoxinnerMove.getNewBoxId() + "不存在，请检查后重试！");
                        }
                        //根据袋id查询袋号
                        ArchiveBag arcBag = archiveBagMapper.selectArchiveBagByBagId(archiveBoxinnerMove.getNewBagId());
                        if (ObjectUtil.isNull(arcBag)) {
                            log.info("档案袋标识" + archiveBoxinnerMove.getNewBagId() + "不存在");
                            throw new ServiceException("档案袋标识" + archiveBoxinnerMove.getNewBagId() + "不存在，请检查后重试！");
                        }
                        archiveBoxinnerMove1.setMoveStatus(BusinessConstants.BOX_MOVE_STATUS);
                        archiveBoxinnerMoveService.updateArchiveBoxinnerMove(archiveBoxinnerMove1);
                    }
                }
            }
        } catch (ServiceException e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new ServiceException(e.getMessage());
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new ServiceException("发生未知异常，事务已回滚");
        }
    }

    /**
     * 修改盒间移位任务状态
     *
     * @param archiveBoxinnerMoveTask 盒间移位任务
     * @return 结果
     */
    @Transactional
    @Override
    public int updateArchiveBoxinnerMoveTaskStatus(ArchiveBoxinnerMoveTask archiveBoxinnerMoveTask) {
        //查询是否传参
        if (ObjectUtil.isNull(archiveBoxinnerMoveTask.getTaskId())) {
            throw new ServiceException("盒间移位单据信息为空，请检查重试！");
        }
        //根据id查询任务详情
        ArchiveBoxinnerMoveTask archiveBoxinnerMoveTask1 = archiveBoxinnerMoveTaskMapper.selectArchiveBoxinnerMoveTaskByTaskId(archiveBoxinnerMoveTask.getTaskId());

        if (BusinessConstants.END_BOX_MOVE_STATUS.equals(archiveBoxinnerMoveTask1.getMoveStatus())) {
            throw new ServiceException("盒间移位任务单号" + archiveBoxinnerMoveTask.getArchMoveNo() + "已移位  ，请勿重复操作！");
        }
        if (ObjectUtil.isNull(archiveBoxinnerMoveTask1)) {
            throw new ServiceException("未查询到盒间移位任务单号" + archiveBoxinnerMoveTask.getArchMoveNo() + "信息，请检查重试！");
        }
        //修改主子表移位状态
        archiveBoxinnerMoveTask1.setMoveStatus(BusinessConstants.END_BOX_MOVE_STATUS);
        archiveBoxinnerMoveTaskMapper.updateArchiveBoxinnerMoveTask(archiveBoxinnerMoveTask1);
        List<ArchiveBoxinnerMove> archiveBoxinnerMoveList = archiveBoxinnerMoveMapper.selectArchiveBoxinnerMoveList(new ArchiveBoxinnerMove() {{
            setTaskId(archiveBoxinnerMoveTask.getTaskId());
        }});

        if (archiveBoxinnerMoveList.size() > 0) {
            for (ArchiveBoxinnerMove archiveBoxinnerMove : archiveBoxinnerMoveList) {
                archiveBoxinnerMove.setMoveStatus(BusinessConstants.END_BOX_MOVE_STATUS);
                archiveBoxinnerMove.setStatus(BusinessConstants.STATUS_SUCESS);
                archiveBoxinnerMoveMapper.updateArchiveBoxinnerMove(archiveBoxinnerMove);

                //修改档案位置
                RoomArchive roomArchive = roomArchiveMapper.selectRoomArchiveById(archiveBoxinnerMove.getArchiveId());
                roomArchive.setBoxNo(archiveBoxinnerMove.getNewBoxNo());
                roomArchiveMapper.updateRoomArchive(roomArchive);

                //根据档案盒id查询盒号
//                ArcBox arcBox = arcBoxMapper.selectArcBoxByBoxId(archiveBoxinnerMove.getNewBoxId());
//                if (ObjectUtil.isNull(arcBox)) {
//                    throw new ServiceException("档案盒标识" + archiveBoxinnerMove.getNewBoxId() + "不存在，请检查后重试！");
//                }
//                //记录档案盒状态
//                ArchiveBoxStatus archiveBoxStatus = new ArchiveBoxStatus();
//                archiveBoxStatus.setAreaNo(arcBox.getAreaNo());
//                archiveBoxStatus.setCabinetNo(arcBox.getCabinetNo());
//                archiveBoxStatus.setBoxBarCode(arcBox.getBoxRfid());
//                archiveBoxStatus.setBoxNo(arcBox.getBoxCode());
//                archiveBoxStatus.setHouseLocationNo(arcBox.getHouseLocationNo());
//
//                archiveBoxStatus.setBoxStatus(BusinessConstants.ARC_STOCK);
//                archiveBoxStatus.setRecordTime(DateUtils.getNowDate());
//                archiveBoxStatus.setPushStatus(BusinessConstants.PUSHSTATUS);
//
//                archiveBoxStatusMapper.insertArchiveBoxStatus(archiveBoxStatus);
            }
        }
        return 1;
    }
}
